from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.common.exceptions import WebDriverException
from webdriver_manager.chrome import ChromeDriverManager
import time

def check_selenium():
    print("检查Selenium环境...")
    
    # 设置Chrome选项
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    
    driver = None
    try:
        print("使用webdriver-manager自动下载和配置ChromeDriver...")
        service = Service(ChromeDriverManager().install())
        print("ChromeDriver准备就绪")
        
        print("尝试启动Chrome浏览器...")
        start_time = time.time()
        driver = webdriver.Chrome(service=service, options=chrome_options)
        end_time = time.time()
        print(f"浏览器启动成功，耗时: {end_time - start_time:.2f}秒")
        
        print("尝试访问百度...")
        start_time = time.time()
        driver.get("https://www.baidu.com")
        end_time = time.time()
        print(f"页面加载成功，耗时: {end_time - start_time:.2f}秒")
        print(f"页面标题: {driver.title}")
        
    except WebDriverException as e:
        print(f"WebDriver错误: {e}")
    except Exception as e:
        print(f"其他错误: {e}")
    finally:
        if driver:
            try:
                driver.quit()
                print("浏览器已关闭")
            except:
                print("关闭浏览器时出错")

if __name__ == "__main__":
    check_selenium()